﻿using Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Application.Commons.Behaviours;

public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    private readonly ILogger<TRequest> _logger;
    private readonly IApplicationDbContext _dbContext;

    public TransactionBehavior(
        IApplicationDbContext dbContext,
        ILogger<TRequest> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        if (_dbContext.Database.IsSqlite())//为了兼容Sqlite数据库
        {
            var response = await next();
            await _dbContext.SaveChangesAsync(cancellationToken);
            return response;
        }
        else
        {
            using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);

            try
            {
                // 在事务开始时添加日志记录
                _logger.LogDebug($"开启事务：{request}");

                var response = await next();

                // 在保存更改前添加日志记录
                _logger.LogDebug($"保存更改：{request}");

                await _dbContext.SaveChangesAsync(cancellationToken);
                await transaction.CommitAsync(cancellationToken);

                // 在事务提交后添加日志记录
                _logger.LogDebug($"提交事务：{request}");

                return response;
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync(cancellationToken);

                // 在发生异常时添加日志记录
                _logger.LogDebug($"回滚事务：{request}");

                throw;
            }
        }
    }
}
